<?php

namespace app\logic;

use GatewayWorker\Lib\Gateway;

use app\model\{Group, GroupUser};

class GroupLogic
{


    /**
     * 创建房间
     * @param $name
     * @param $uid
     * @return false|int|string
     */
    public static function add($name, $uid)
    {
        if ($group_id = Group::add($name, $uid)) {
            Gateway::$registerAddress = config('gateway_worker.registerAddress');
            $client_id = Gateway::getClientIdByUid($uid);
            if ($client_id) {
                foreach ($client_id as $value) {
                    Gateway::joinGroup($value, $group_id);
                }
            }
            return $group_id;
        }
        return false;
    }

    /**
     * 加入房间
     * @param $group_id
     * @param $uid
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function join($group_id, $uid)
    {
        if (Group::where('id', $group_id)->field('id')->find()) {
            if ($GroupUser = GroupUser::where('group_id', $group_id)->where('uid', $uid)->field('id,df')->find()) {
                if ($GroupUser->df)
                    GroupUser::where('id', $GroupUser->id)->update(['df' => 0]);
            } else {
                GroupUser::insert(['uid' => $uid, 'group_id' => $group_id]);
            }
            Gateway::$registerAddress = config('gateway_worker.registerAddress');
            $client_id = Gateway::getClientIdByUid($uid);
            if ($client_id) {
                foreach ($client_id as $value) {
                    Gateway::joinGroup($value, $group_id);
                }
            }
            return true;
        } else {
            return false;
        }
    }
}